// 人员核对列表
<template>
    <div>
        <v-accordion :title="title" class="infoList noBorder" :disabled="disabledClickTitle" :opened="opened">
            <f7-list media-list class="search-list" v-if="checkList.length > 0">
                <li
                    v-for="(item, index) in checkList"
                    :key="index"
                    class="content-box"
                >
                    <div class="person-info">
                        <img
                            v-if="!item.personPhotoAttachId"
                            src="../../assets/img/qzjx/defaultAvatar.png"
                            width="50"
                            class="sculpture"
                            height="50"
                            @click="openBook(item)"
                        />
                        <img
                            v-else
                            :src="$util.getImgSrc(item.personPhotoAttachId)"
                            width="50"  
                            class="sculpture"
                            height="50"
                            @click="openBook(item)"
                        />
                        <div class="right-box">
                            <div class="right-box-left">
                                <div class="code">
                                    {{ item.personName }}
                                    <!-- <span class="certType" v-if="item.certSource==1">
                                        <img src="@/assets/img/qzjx/local.png" alt="">本系统
                                    </span>
                                    <span class="certType local" v-if="item.certSource==2">
                                        <img src="@/assets/img/qzjx/province.png" alt="">省系统
                                    </span> -->
                                    <span style="color:#F37A7B;font-size: 12px;font-weight: 400;" v-if="item.isWarn">【一年内存在违章记录】</span>
                                    <span style="color:#F37A7B;font-size: 12px;font-weight: 400;" v-if="item.changeOrgNum>=3">【一年内变更过{{item.changeOrgNum}}家企业】</span>
                                    <span style="color:#F37A7B;font-size: 12px;font-weight: 400;" v-if="item.staffStatus=='3'">【已移除】</span>
                                    <span style="color:#F37A7B;font-size: 12px;font-weight: 400;" v-if="item.staffStatus=='4'">【变更】</span>
                                </div>
                                <div style="margin-bottom:5px">{{item.personMobile}}</div>
                                <span>{{ item.jobType }}</span>
                            </div>
                            <div class="right-box-right" style="flex-shrink: 0;">
                                <div class="name-box" v-if="item.authTime">
                                    <f7-icon
                                        f7="checkmark_seal_fill"
                                        size="16px"
                                    ></f7-icon>
                                    <span>{{item.authType==2?'人工识别':'认证通过'}}</span>
                                </div>
                                <div
                                    class="name-box"
                                    @click="checkItem(item, index)"
                                    v-if="!item.authTime && !disabled"
                                >
                                    <span class="tag" v-if="isUmSdk&&!item.showAdd">待认证</span>
                                    <qm-file-upload
                                        :uploadId="listName+index"
                                        ref="checkPersonPic"
                                        :showMsg="false"
                                        :galleryOptions="{
                                            multiple: true,
                                            maximum: 9,
                                        }"
                                        :disabled="disabled"
                                        accept=".jpg,.jpeg,.png"
                                        extensions="jpg,jpeg,png"
                                        :params="{
                                            type: 'attach',
                                            dataKey: item.staffId,
                                            bizType: 'COMPARE_PIC_ATTACH',
                                        }"
                                        @success="(file)=>checkFace(file,index,item)"
                                        v-if="!isUmSdk&&!item.showAdd"
                                        :actionsOneGroup="actionsOneGroup"
                                        :acceptCount="1"
                                    >
                                    </qm-file-upload>
                                </div>
                                <qm-file-upload
                                    class="other11"
                                    v-if="item.showAdd&&!item.authTime && !disabled"
                                    :uploadId="listName+index"
                                    ref="checkPersonPic"
                                    :showMsg="false"
                                    :galleryOptions="{
                                        multiple: true,
                                        maximum: 9,
                                    }"
                                    :disabled="disabled"
                                    accept=".jpg,.jpeg,.png"
                                    extensions="jpg,jpeg,png"
                                    :params="{
                                        type: 'attach',
                                        dataKey: item.staffId,
                                        bizType: 'MANUAL_STAFF_PIC',
                                    }"
                                    :acceptCount="1"
                                    @success="(file)=>getAuth(index,2,item)"
                                    :actionsOneGroup="[1]"
                                >
                                </qm-file-upload>
                               
                                <div class="name-box"  style="padding-right:10px;">
                                    <span class="tag-no" v-if="!item.authTime && disabled">未认证</span>
                                    <span class="tag-change"  v-if="!item.authTime && item.staffStatus != 4 && canUpdatePerson" @click="onChangePerson(item,index)">变更</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- <div class="change-info">人员由李国梦变更为罗晓兰<span>取消变更</span></div> -->
                </li>
            </f7-list>
            <v-empty v-else description="暂无数据" />
        </v-accordion>
        <van-popup
            v-model="visible"
            position="bottom"
            class="popup-bg"
            get-container="body"
            :style="{ height: '100%', background: '#F4F6F9' }"
            :lock-scroll="false"
        >
            <f7-page>
                <f7-navbar>
                    <f7-nav-left>
                        <f7-link
                            @click="visible = false"
                            icon-material="chevron_left"
                            force
                        ></f7-link>
                    </f7-nav-left>
                    <f7-nav-title>资格证书</f7-nav-title>
                    <f7-nav-right> </f7-nav-right>
                </f7-navbar>
                <div class="content-list">
                    <img :src="fileObj.path" alt="" width="100%" v-if="fileObj.type=='image'">
                    <iframe
                        :src="`static/pdfjs/web/viewer.html?file=${fileObj.path}`"
                        style="border: 0px !important; margin-top: 2px"
                        width="100%"
                        height="600px"
                        v-if="fileObj.type=='.pdf'"
                    ></iframe>
                </div>
                <f7-toolbar position="bottom" no-shadow class="fff" v-if="!disabled">
                    <f7-button fill class="submit-btn" @click="save()">{{
                        selectItem.authTime ? '认证通过' : '待认证'
                    }}</f7-button>
                </f7-toolbar>
            </f7-page>
        </van-popup>
        <!-- 变更人员 -->
        <v-popup-person-update v-model="showUpdatePerson" :beforeStaffId="beforeStaffId"  :caseId="caseId" :extraParams="extraParams" @changePersonSuccess="changePersonSuccess"></v-popup-person-update>
    </div>
</template>

<script>
import Config from '@/libs/config'
import Upload from '@/libs/framework/upload'
import Util from '@/libs/framework/util'


export default {
    name: 'v-person-list',
    props: {
        list: {
            // 步骤标题数组
            type: Array,
            default: () => {
                return []
            },
        },
        title: {
            type: String,
        },
        disabled: {
            type: Boolean,
            default: false,
        },
        // 是否展开
        opened:{
            type:Boolean,
            default:true
        },
        // 是否禁用
        disabledClickTitle:{
            type:Boolean,
            default:true
        },
        // 上传方式的选择 1相册 2拍照 3文件
        actionsOneGroup: {
            type: Array,
            default: () => {
                return [1]
            },
        },
        listName:{
            type:String,
            default:'personCheck'
        },
        canUpdatePerson:{// 是否可进行人员变更
            type:Boolean,
            default:()=>{
                return false;
            }
        }
    },
    computed: {
        isUmSdk() {
            if (process.env.CONFIG_TYPE.includes('UM_PROD')) {
                return true
            } else {
                return false
            }
        },
    },
    data() {
        return {
            download: Config.api.download,
            personPhotoAttachId: null,
            staffId: null,
            currentIndex: null,
            selectItem: {},
            visible: false,
            fileObj:{
                path: '',
                type:'image',
            },
            showAdd:false,
            checkList:[],
            showUpdatePerson:false,// 变更人员弹窗 
            extraParams:{},// 变更人员弹窗的传参
            beforeStaffId:'',
            caseId:'',
            changePersonItem:null,
            changePersonIndex:null
        }
    },
    mounted () {
        this.checkList=JSON.parse(JSON.stringify(this.list))
    },
    methods: {
        checkItem(item, index) {
            let that=this
            if (!item.authTime && !this.disabled) {
                let currentItem=this.checkList[index]
                this.personPhotoAttachId = currentItem.personPhotoAttachId
                // this.personPhotoAttachId = item.personPhotoAttachId
                this.staffId = currentItem.staffId
                this.currentIndex = index
                if (this.isUmSdk) {
                    that.$f7.preloader.show();
                    this.$util.getPromise('/mobileApi/base/account/getFaceAttach', {personId:item.personId})
                    .then(res => {
                        if(res&&res.success&&res.parameters&&res.parameters.lastFaceAttach){
                            const {attachmentId} = res.parameters.lastFaceAttach
                            const faceUrl = Config.api.download+'?attachmentId='+attachmentId
                            that.$f7.preloader.hide();
                            umSdk.startFaceMatch({
                                faceUrl, // 人脸库中图片地址（非必填）
                                success: function(res) {
                                    that.$f7.preloader.hide();
                                    console.log(res.score) // 相似度：0 - 100
                                    if(Number(res.score)>=70){
                                        that.$emit('check', index)
                                        item.authTime=1
                                        that.getAuth(index,1,item)
                                    }else{
                                        if(!item.authNum)item.authNum=0
                                        if(!item.showAdd) item.showAdd=false
                                        item.authNum++
                                        if(item.authNum>=3){
                                            that.$dialog.confirm({
                                                message: '本次识别不成功，是否继续识别? (选择人工识别，请拍人脸照片)',
                                                confirmButtonText:'人工识别',
                                                cancelButtonText:'自动识别',
                                                confirmButtonColor:'#1990FF',
                                                cancelButtonColor:'#242424',
                                                title:'提示'
                                            })
                                            .then(() => {
                                                item.showAdd=true
                                                that.checkList.splice(index,1,item)
                                            })
                                            .catch(() => {
                                                item.showAdd=false
                                                that.checkItem(item,index)
                                                that.checkList.splice(index,1,item)
                                            });
                                        }else{
                                            that.$toast('人脸相似度为'+Number(res.score)+'，验证失败！')
                                            item.showAdd=false
                                            that.checkList.splice(index,1,item)
                                        }
                                    }
                                },
                                fail: function(err) {
                                    
                                }
                            })

                        }else{
                            that.$f7.preloader.hide();
                            that.$toast('人脸库中暂无对应人脸照片')
                        }
                    })
                    .catch(e=>{
                        that.$f7.preloader.hide();
                        console.log(e);
                        that.$toast('获取数据失败')
                    });
                }
            } else {
                this.visible = false
            }
        },
        checkFace(file,index,item) {
            let attachmentId = file.response?file.response.parameters.file.key:file.key
            this.$f7.preloader.show();
            this.$f7.request.post(
                `/app/external/faceComparison/compare`,
                {
                    attachmentId: attachmentId,
                    personPhotoAttachId: this.checkList[index].personPhotoAttachId,
                },
                (r) => {
                    r = JSON.parse(r)
                    if (r && r.success) {
                        this.$f7.preloader.hide();
                        this.getAuth(index,1,item)
                    } else {
                        this.$f7.preloader.hide();
                        if(this.$refs.checkPersonPic) this.$refs.checkPersonPic[0].removeFile(file,0,true)
                        if(!item.authNum)item.authNum=0
                        if(!item.showAdd) item.showAdd=false
                        item.authNum++
                        if(item.authNum>=3){
                            this.$dialog.confirm({
                                message: '本次识别不成功，是否继续识别? (选择人工识别，请拍人脸照片)',
                                confirmButtonText:'人工识别',
                                cancelButtonText:'自动识别',
                                confirmButtonColor:'#1990FF',
                                cancelButtonColor:'#242424',
                                title:'提示'
                            })
                            .then(() => {
                                item.showAdd=true
                                this.checkList.splice(index,1,item)
                            })
                            .catch(() => {
                                item.showAdd=false
                                this.checkList.splice(index,1,item)
                            });
                        }else{
                            this.$toast(r.message || '网络错误，请稍后重试')
                            this.checkList.splice(index,1,item)
                        }
                    }
                },
                (e)=>{
                    this.$f7.preloader.hide();
                }
            )
        },
        // 提交认证方法
        getAuth(index,authType,item){
            this.$f7.preloader.show();
            this.$f7.request.post(
                `/app/equipment/eqmCaseStaff/authPerson`,
                {
                    staffId: this.checkList[index].staffId,
                    type: 1,
                    authType,
                },
                (r) => {
                    this.$f7.preloader.hide();
                    r = JSON.parse(r)
                    if (r && r.success) {
                        this.$emit('check', index)
                        item.authTime=1
                        this.$toast('认证成功')
                        item.authType=authType
                        this.checkList.splice(index,1,item)
                        this.$forceUpdate()
                    } else {
                        this.$toast(
                            r.message || '网络错误，请稍后重试'
                        )
                    }
                },
                (e)=>{
                    this.$f7.preloader.hide();
                }
            )
        },
        openBook(item, index) {
            this.selectItem = item
            this.currentIndex = index
            // let fileType=item.certScanCopyAttachId
            // let id=item.certScanCopyAttachFileType
            // item.certScanCopyAttachFileType=fileType
            // item.certScanCopyAttachId=id
            let imgTypes=[".png", ".jpg", ".jpeg", ".bmp", ".webp", ".gif"]
            if (imgTypes.includes(item.certScanCopyAttachFileType.toLowerCase())) {
                this.fileObj.type=='image'
            }else if(item.certScanCopyAttachFileType.toLowerCase()=='.pdf'){
                this.fileObj.type='.pdf'
            }else{
                this.fileObj.type=item.certScanCopyAttachFileType
            }
            // if(this.fileObj.type=='image'||this.fileObj.type=='pdf'){
            if(this.fileObj.type=='image'){
                this.fileObj.path = this.$util.getFileSrc(item.certScanCopyAttachId)
                this.visible = true
            }else if(this.fileObj.type=='.pdf'){
                this.fileObj.path = encodeURIComponent(this.$util.getFileSrc(item.certScanCopyAttachId))
            }else{
                if(this.isUmSdk){
                    let  url = `${Config.api.viewOpenFile}/${item.certScanCopyAttachId}${item.certScanCopyAttachFileType}`
                    umSdk.scanFile({
                        downloadurl: url, // 文件预览网络地址
                        filename: '',
                        success: function () { },
                        fail: function (err) { }
                    })
                }else if(window.qmSdk){
                    let params = {
                        filename: '',
                        downloadurl: this.$util.getFileSrc(item.certScanCopyAttachId),
                    };
                    window.qmSdk.scanFile(params);
                }else if(window.plus){
                    window.plus.downloadFile('', item.certScanCopyAttachId, this, true, {
                        askRedownload: false
                    })
                }else{
                    self.$util.downloadFile(
                        '',
                        item.certScanCopyAttachId,
                        self,
                        this.$util.getFileSrc(item.certScanCopyAttachId),
                        true,
                        { askRedownload: false }
                    );
                }
            }
        },
        save() {
            this.checkItem(this.selectItem, this.currentIndex)
        },
        // 变更人员
        onChangePerson(item,index){
            this.changePersonItem = item;
            this.changePersonIndex = index;
            this.beforeStaffId = item.staffId;
            this.caseId = item.caseId;
            this.extraParams = {
                jobTypeIds:item.workType,
                personStatus:1
            }
            this.showUpdatePerson = true;
        },
        // 变更人员成功
        changePersonSuccess(afterStaff){
            this.changePersonItem = afterStaff;
            this.changePersonItem.staffStatus = '4';
            this.checkList.splice(this.changePersonIndex,1,this.changePersonItem)
        }
    },
    watch: {
        list:{
            handler(val){
                if(this.checkList.length>0){
                    let newCheck=JSON.parse(JSON.stringify(this.checkList))
                    let assginFunc=(item,index)=>{
                        return new Promise((resolve, reject) => {
                            let newItem=Object.assign(newCheck[index],item)
                            resolve(newItem)
                        })
                    }
                    this.checkList=val.map((item,index)=>{
                        item=Object.assign(item,newCheck[index])
                        return item
                    })
                    this.$forceUpdate()
                }else{
                    this.checkList=JSON.parse(JSON.stringify(val))
                }
            },
            immediate:true,
            deep:true,
        }
    }
}
</script>

<style lang="less" scoped>
@import url('../../assets/css/commonPage.less');

.noBorder {
    @{deep}.title-solid {
        background: #fff !important;
    }

    @{deep}.item-content {
        padding-left: 6px !important;
    }

    margin: 10px 16px !important;
    box-shadow: 0px 3px 8px 0px rgba(165, 201, 255, 0.1);
    background: #fff;
    border-radius: 8px;
    overflow: hidden;
    padding-bottom: 10px;
}

li {
    &:first-child .content-box {
        margin-top: 0;
    }

    .content-box {
        background: #fff;
        margin-bottom: 0;
        padding: 0;
        padding-left: 10px;
        padding-right: 10px;
        padding-bottom: 15px;
        display: block;
        &:last-child{
            padding-bottom: 0;
        }
        box-shadow: none;
        @{deep}.pic_upload {
            span {
                margin: 0 5px 0 0;
                div.img-div{
                    width:75px;
                    height:75px;
                }
            }
        }
        .person-info{
            display: flex;
            align-items: center;
        }
        .change-info{
            color: #333;
            background: #ecf5ff;
            font-size: 12px;
            padding: 7px 10px;
            border-radius: 4px;
            margin-top: 8px;
            span{
                cursor: pointer;
                color: @mainColor;
                margin-left: 10px;
            }
        }
    }

    .sculpture {
        border-radius: 50px;
    }

    .right-box {
        margin-left: 10px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 12px;

        .right-box-left {
            color: #8995ac;

            .code {
                font-size: 14px;
                font-weight: 600;
                color: #242424;
            }
        }

        .right-box-right {
            color: #25c670;
            .tag {
                color: #1990ff;
                border-color: #1990ff;
                border-radius: 11px;
                padding: 3px 8px;
            }
            .tag-no{
                color: #8995AC;
            }
            .tag-change{
                color: #8995AC;
                position: relative;
                margin-left: 6px;
                padding-left: 7px;
            }
        }
    }
}

@{deep}.accordion-item{
    .item-content i{
        display: none;
    }
}
.certType{
  display: inline-flex;
  align-items: center;
  background: #F1F6FF;
  padding: 5px 8px;
  color: #5D75F6!important;
  font-size: 12px!important;
  border-radius: 25px;
  height: 15px;
  font-weight: 500;
  img{
    width: 16px;
    margin-right: 5px;
  }
  &.local{
    background: #FFF9D9;
    color: #FF821C;
  }
}
</style>
